
package ms.platform.progress.service;

import ms.platform.plan.dto.ModelDto;
import ms.platform.plan.dto.TargetDto;
import ms.platform.plan.model.ModelPlan;
import ms.platform.plan.model.ModelProcessPlan;
import ms.platform.progress.dao.FactoryPlanDao;
import ms.platform.progress.dao.IndexAuditDao;
import ms.platform.progress.dao.ProgressViewDao;
import ms.platform.progress.dto.AnnexDto;
import ms.platform.progress.dto.MeterUsedDto;
import ms.platform.progress.dto.ProgressDetailDto;
import ms.platform.progress.dto.ProgressDto;
import ms.platform.progress.dto.ProgressRecordVo;
import ms.platform.progress.model.AuditResult;
import ms.platform.util.DateUtil;
import ms.platform.util.PageUtils;
import ms.platform.util.StringUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(propagation=Propagation.SUPPORTS)
public class FactoryPlanService {
	
	@Autowired
	FactoryPlanDao factoryPlanDao;
	
	@Autowired
	IndexAuditDao indexAuditDao;
	
	@Autowired
	ProgressViewDao progressViewDao;
	/**
	 * 厂商查询我的计划列表
	 * @param map
	 * @return
	 */
	public List<ModelDto> queryPageBusModelPlanList(Map<String, Object> map){
		List<ModelDto> modelList = factoryPlanDao.queryPageBusModelPlanList(map);
		for (ModelDto modelDto : modelList) {
			Map<String, Object> maps = new HashMap<String, Object>();
			maps.put("modelPlanId", modelDto.getModelPlanId());
			maps.put("recordDate", DateUtil.getDateString(new Date(), "yyyy-MM-dd"));
			String id = factoryPlanDao.queryIsExist(maps);
			if(StringUtils.isNotEmpty(id)){
				modelDto.setFlag("0");
			}else{
				modelDto.setFlag("1");
			}
			ProgressRecordVo pv = progressViewDao.queryIsSubmitRecord(maps);
			if(null != pv){
				if(0==pv.getSubmitFlag()){
					modelDto.setSubmitFlagText("已保存");
				}else if(1==pv.getSubmitFlag()){
					modelDto.setSubmitFlagText("已提交");
				}else{
					modelDto.setSubmitFlagText("未提交");
				}
			}
			String recordId = factoryPlanDao.getRecordId(modelDto.getModelPlanId());
			String result = factoryPlanDao.getAuditResult(modelDto.getModelPlanId());
			if(StringUtils.isNotEmpty(result)){
				modelDto.setLastAuditResult(result);
			}else{
				if(StringUtils.isNotEmpty(recordId)){
					modelDto.setLastAuditResult("3");
				}else{
					modelDto.setLastAuditResult("1");
				}
			}
		}
		return modelList;
	}
	
	/**
	 * 分页查询获取总条数
	 * @param map
	 * @return
	 */
	public Integer queryPageBusModelPlanCount(Map<String, Object> map){
		return factoryPlanDao.queryPageBusModelPlanCount(map);
	}

	/**
	 * 获取工序信息
	 *
	 * @param id
	 * @return
	 */
	public ProgressDto queryModelProcessByPlanId(Integer id, boolean endtime) {
		ProgressDto proDto = new ProgressDto();
		Date reportDate = DateUtil.getNowDate();
		proDto.setModelPlanId(id);
		proDto.setReportDate(DateUtil.getDateString(reportDate, "yyyy-MM-dd"));
		String eng = factoryPlanDao.getEngineering(id);
		proDto.setEngineering(eng);
		List<ModelProcessPlan> processList = factoryPlanDao.queryModelProcessByPlanId(id);
		////如果计划时间已经结束 取最后一个工序
		int processSize = processList.size();
		int proTemp = 1;
		for (ModelProcessPlan modelProcessPlan : processList) {
			boolean flag = DateUtil.isEffectiveDate(reportDate, modelProcessPlan.getPlanStartTime(), modelProcessPlan.getPlanEndTime());
			if (endtime && (processSize == proTemp)) {//如果计划时间已经结束，跳过此校验
				flag = true;
			}
			if (flag) {
				long day = DateUtil.getDayByDateSubraction(reportDate, modelProcessPlan.getPlanStartTime());
				proDto.setModelCode(modelProcessPlan.getModelCode());
				proDto.setPlanProgress(modelProcessPlan.getProcessName());
				proDto.setPlanStartTime(modelProcessPlan.getPlanStartTime());
				proDto.setPlanTotalTime(modelProcessPlan.getPlanTotalTime());

				DecimalFormat df = new DecimalFormat("#");
				if (day == 0) {
					proDto.setNowDay(1L);
					proDto.setPlanPro(df.format(100 / (double) modelProcessPlan.getPlanTotalTime() * 1));
				} else if (day == modelProcessPlan.getPlanTotalTime()) {
					proDto.setNowDay(day);
					proDto.setPlanPro("100");
				} else {
					proDto.setNowDay(day);
					proDto.setPlanPro(df.format(100 / (double) modelProcessPlan.getPlanTotalTime() * day));
				}
				if (StringUtils.isEmpty(modelProcessPlan.getTargetPre())) {
					proDto.setTargetPre("0");
				} else {
					proDto.setTargetPre(modelProcessPlan.getTargetPre());
				}
				ModelProcessPlan currentProgress = factoryPlanDao.queryCurrentProgress(id);
				if (null != currentProgress && StringUtils.isNotEmpty(currentProgress.getProcessName())) {
					proDto.setCurrentPro(currentProgress.getProcessName());
					proDto.setModelProcessId(currentProgress.getId());
					proDto.setAccStartTime(currentProgress.getPlanStartTime());
					proDto.setAccTotalTime(currentProgress.getPlanTotalTime());
				} else {
					ModelProcessPlan currentProgressTwo = factoryPlanDao.queryCurrentProgressTwo(id);
					if(null != currentProgressTwo){
						proDto.setCurrentPro(currentProgressTwo.getProcessName());
						proDto.setModelProcessId(currentProgressTwo.getId());
						proDto.setAccStartTime(currentProgressTwo.getPlanStartTime());
						proDto.setAccTotalTime(currentProgressTwo.getPlanTotalTime());
					}
				}
				if (endtime) {//如果计划时间已经结束，计划比例为100%
					proDto.setPlanPro("100");
				}
				break;
			}
			proTemp++;
		}
		return proDto;
	}
	
	/**
	 * 保存进度报告
	 * @param progressDto
	 */
	public void saveProgressRecord(ProgressDto progressDto,ProgressDetailDto progressDetailDto,List<AnnexDto> annexList,String userId){
		Map<String,Object> map1 = new HashMap<String,Object>();
		Map<String,Object> map2 = new HashMap<String,Object>();
		map1.put("modelPlanId", progressDto.getModelPlanId());
		map1.put("recordDate", DateUtil.getDateString(new Date(), "yyyy-MM-dd"));
		ProgressDto recordDto = factoryPlanDao.queryProcessRecordByPlanIdAndReportTime(map1);
		if(null != recordDto){
			progressDto.setId(recordDto.getId());
			progressDetailDto.setRecordId(recordDto.getId());
			factoryPlanDao.saveProgressDetail(progressDetailDto);
			if(null != progressDetailDto.getId()){
				progressDto.setStatus("0");
				progressDto.setReviewStatus("0");
				progressDto.setRecordDetailId(progressDetailDto.getId());
				factoryPlanDao.updatePlanProgressRecord(progressDto);
			}
			if(null != progressDetailDto.getId()){
				for (AnnexDto annexDto : annexList) {
					annexDto.setRecordDetailId(progressDetailDto.getId());
		        	annexDto.setInsertedBy(userId);
		        	annexDto.setInsertedAt(new Date());
		        	annexDto.setUpdatedBy(userId);
					annexDto.setUpdatedAt(new Date());
				}
				if(annexList.size()>0){
					factoryPlanDao.saveAnnex(annexList);
				}
			}
		}else{
		progressDto.setStatus("0");
		progressDto.setReportDate(DateUtil.getDateString(new Date(), "yyyy-MM-dd"));
		progressDto.setInsertedAt(new Date());
		progressDto.setInsertedBy(userId);
		progressDto.setUpdatedAt(new Date());
		progressDto.setUpdatedBy(userId);
		progressDto.setReviewStatus("0");
		progressDto.setProgressStatus("0");
		factoryPlanDao.saveProgressRecord(progressDto);
		if(null != progressDto.getId()){
			progressDetailDto.setRecordId(progressDto.getId());
			factoryPlanDao.saveProgressDetail(progressDetailDto);
			progressDto.setRecordDetailId(progressDetailDto.getId());
			factoryPlanDao.updatePlanProgressRecord(progressDto);
		}
		if(null != progressDetailDto.getId()){
			for (AnnexDto annexDto : annexList) {
				annexDto.setRecordDetailId(progressDetailDto.getId());
	        	annexDto.setInsertedBy(userId);
	        	annexDto.setInsertedAt(new Date());
	        	annexDto.setUpdatedBy(userId);
				annexDto.setUpdatedAt(new Date());
			}
			if(annexList.size()>0){
				factoryPlanDao.saveAnnex(annexList);
			}
		}
		}
		if(null != progressDto.getModelProcessId()){
			String accStartTime = factoryPlanDao.getAccStartTimeByid(progressDto.getModelProcessId());
			if(StringUtils.isEmpty(accStartTime)){
				//更新工序开始时间
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("id", progressDto.getModelProcessId());
				map.put("accStartTime", new Date());
				factoryPlanDao.updateModelProgressPlanTime(map);
			}
		}
		factoryPlanDao.updateLastReportTime(map1);
	}
	
	/**
	 * 我的进度报列表
	 * @return
	 */
	public List<ProgressDto> myProgressReportList(Map<String, Object> map,HttpServletRequest request,String userId){
		map.put("userId", userId);
		map.put("count", factoryPlanDao.myProgressReportCount(map));
		List<ProgressDto> list = factoryPlanDao.myProgressReportList(PageUtils.Page(request,map));
		PageUtils.calculate(map);
		return list;
	}

	/**
	 * 根据计划台账id查询台账明细
	 *
	 * @param id
	 * @return
	 */
	public ProgressDetailDto getProgressDetailById(Integer id, boolean temp,boolean endtime,boolean isShenhe) {
		ProgressDto progressDto = new ProgressDto();
		ProgressDetailDto detailDto = new ProgressDetailDto();
		AuditResult auditResult = new AuditResult();
		if (null != id) {
			progressDto = factoryPlanDao.getProgressRecordById(id);
			if (progressDto != null) {
				detailDto.setModelCode(progressDto.getModelCode());
			}
			if (null != progressDto.getRecordDetailId()) {
				detailDto = factoryPlanDao.getProgressRecordDetailById(progressDto.getRecordDetailId());
				if (null != detailDto) {
					if (null != detailDto.getReviewRcdId()) {
						auditResult = indexAuditDao.getAduitResult(detailDto.getReviewRcdId());
					}
				}
			}
		}
		if (null != progressDto) {
			ProgressDto dto;
			dto = this.queryModelProcessByPlanId(progressDto.getModelPlanId(), endtime);
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
			String newDate = df.format(new Date());
			if (null != detailDto) {
				detailDto.setModelCode(dto.getModelCode());
				detailDto.setEngineering(dto.getEngineering());
				detailDto.setModelPlanId(progressDto.getModelPlanId());
				detailDto.setPlanProgress(progressDto.getPlanProcessName() == null ? dto.getPlanProgress() : progressDto.getPlanProcessName());
				//大屏进入这里,为true 当天的如果数据库为空,获取计算的,不为空获取数据库的
				if (temp) {
					if (DateUtil.middate(newDate, progressDto.getReportDate(), df) == 0) {
						detailDto.setPlanPro(dto.getPlanPro());
					}
				}
				//不是大屏走这里
				if (!temp) {
					detailDto.setPlanPro(dto.getPlanPro());
				}

				detailDto.setTargetPre(dto.getTargetPre());
				detailDto.setModelProcessId(dto.getModelProcessId());

				//如果计划时间已经结束，汇报日期则为今天
				if (endtime) {
					if (isShenhe) {//如果是审核进这里
						detailDto.setReportDate(progressDto.getReportDate());
					}else{
						detailDto.setReportDate(newDate);
					}
				}else{
					detailDto.setReportDate(progressDto.getReportDate());
				}
				detailDto.setCurrentPro(progressDto.getCurrentPro() == null ? dto.getCurrentPro() : progressDto.getCurrentPro());
				detailDto.setStatus(auditResult.getResult());
				detailDto.setAdvise(auditResult.getReviewAdvise() == null ? auditResult.getAdvise() : auditResult.getReviewAdvise());
				detailDto.setNowDay(dto.getNowDay());
				detailDto.setPlanTotalTime(dto.getPlanTotalTime());
				detailDto.setPlanStartTime(dto.getPlanStartTime());
				detailDto.setAccStartTime(dto.getAccStartTime());
				detailDto.setAccTotalTime(dto.getAccTotalTime());
			}
		}
		return detailDto;
	}
	/**
	 * 获取附件信息
	 * @param id
	 * @return
	 */
	public List<AnnexDto> getProgressAnnexList(Integer id){
		List<AnnexDto> annexList = factoryPlanDao.getProgressAnnexListById(id);
		return annexList;
	}
	/**
	 * 修改进度详细
	 * @param progressDetailDto
	 * @param annexList
	 */
	public void editProgressDetail(ProgressDetailDto progressDetailDto,List<AnnexDto> annexList,String userId){
		factoryPlanDao.updateProgressDetailById(progressDetailDto);
		List<AnnexDto> annexDtoList = new ArrayList<AnnexDto>();
		for (AnnexDto annexDto : annexList) {
			if(null == annexDto.getId()){
				annexDto.setRecordDetailId(progressDetailDto.getId());
				annexDto.setInsertedBy(userId);
	        	annexDto.setInsertedAt(new Date());
	        	annexDto.setUpdatedBy(userId);
				annexDto.setUpdatedAt(new Date());
				annexDtoList.add(annexDto);
			}
		}
		if(annexDtoList.size()>0){
			factoryPlanDao.saveAnnex(annexDtoList);
		}
	}
	/**
	 * 删除附件
	 * @param id
	 */
	public void deleteAnnexByid(Integer id){
		factoryPlanDao.deteleAnnexById(id);
	}
	/**
	 * 厂商接受任务
	 */
	public void accept(Map<String,Object> map){
		factoryPlanDao.accept(map);
	}
	
	public ProgressDto queryProcessRecordByPlanIdAndReportTime(Map<String,Object> map){
		return factoryPlanDao.queryProcessRecordByPlanIdAndReportTime(map);
	}
	/**
	 * 保存才发信息
	 * @param meterUsedDto
	 */
	public void saveMeterUsedRecord(MeterUsedDto meterUsedDto){
		/*List<ModelMeterPlan> meterList = factoryPlanDao.queryMeterInfo(map);
		Integer userAmount = meterUsedDto.getUsedAmount();
		for (ModelMeterPlan modelMeterPlan : meterList) {
			Map<String,Object> maps = new HashMap<String,Object>();
			if(userAmount>0){
				if(userAmount>=modelMeterPlan.getPlanNum()){
					maps.put("id", modelMeterPlan.getId());
					maps.put("avaliablAmount", 0);
					//busModelMeterPlanDao.updateModelMeterAvaliablAmount(map);
					userAmount = userAmount-modelMeterPlan.getPlanNum();
				}else{
					maps.put("id", modelMeterPlan.getId());
					maps.put("avaliablAmount", modelMeterPlan.getPlanNum()-userAmount);
					//busModelMeterPlanDao.updateModelMeterAvaliablAmount(map);
					userAmount = 0;
				}
			}else if(userAmount == 0){
				break;
			}else{
				throw new BusinessException("使用数超过支给数");
			}
		}*/
		factoryPlanDao.saveMeterUsedRecord(meterUsedDto);
	}
	public List<MeterUsedDto> queryMeterUsedDetails(Map<String,Object> map,HttpServletRequest request){
		map.put("count", factoryPlanDao.queryMeterUsedDetailsCount(map));
		List<MeterUsedDto> list = factoryPlanDao.queryMeterUsedDetails(PageUtils.Page(request,map));
		PageUtils.calculate(map);
		return list;
	}

	/**
	 * 保存进度报告
	 */
	public void saveReportFreq(ModelDto modelDto){
		Map<String,Object> mapFreq = new HashMap<String,Object>();
		mapFreq.put("modelPlanId", modelDto.getModelPlanId());
		mapFreq.put("reportFreq", modelDto.getReportFreq());
		factoryPlanDao.updateLastReportTime(mapFreq);
	}

	/**
	 * 频次提醒
	 * @return
	 */
	public List<ModelDto> myTimingScheduleList(String id) {
		List<ModelDto> list = factoryPlanDao.myTimingScheduleList(id);
		return list;
	}
	/**
	 * 获取所有工序
	 * @param modelPlanId
	 * @return
	 */
	public List<TargetDto> getAllProcessName(Integer modelPlanId){
		List<TargetDto> list = factoryPlanDao.getAllProcessName(modelPlanId);
		return list;
	}
	public ProgressDto getPlanStartTimeByProcessName(Map<String,String> map){
		ProgressDto dto = factoryPlanDao.getPlanStartTimeByProcessName(map);
		Map<String,String> map2 = new HashMap<String,String>();
		map2.put("modelPlanId", map.get("modelPlanId"));
		map2.put("currentPro", map.get("planProgressName"));
		ProgressDto dto2 = factoryPlanDao.getPlanStartTimeByProcessName(map2);
		Map<String,Object> map3 = new HashMap<String,Object>();
		map3.put("modelPlanId", map.get("modelPlanId"));
		map3.put("startTime", dto.getPlanStartTime());
		if (!StringUtil.isNullOrBlock(dto2)) { //不为空时进入
			map3.put("endTime", dto2.getPlanStartTime());
			int c = DateUtil.compare_date(DateUtil.getDateString(dto.getPlanStartTime(),"yyyy-MM-dd"), DateUtil.getDateString(dto2.getPlanStartTime(),"yyyy-MM-dd"));
			if(c>0){
				map3.put("startTime", dto2.getPlanStartTime());
				map3.put("endTime", dto.getPlanStartTime());
			}else{
				map3.put("startTime", dto.getPlanStartTime());
				map3.put("endTime", dto2.getPlanStartTime());
			}
		}
		String day = factoryPlanDao.sumPlantotalTime(map3);
		if(StringUtils.isNotEmpty(day)){
			dto.setDay(day);
		}else{
			dto.setDay("0");
		}
		return dto;
	}
	
	/**
	 * 根据id获取材料使用记录
	 * @param id
	 * @return
	 */
	public MeterUsedDto getMeterUsedRecord(Integer id){
		return factoryPlanDao.getMeterUsedRecord(id);
	}
	
	/**
	 * 修改材料使用记录
	 * @param dto
	 * @return
	 */
	public void usedMeterEdit(MeterUsedDto dto){
		 factoryPlanDao.usedMeterEdit(dto);
	}
	public String getPrevAccStartTime(Map<String,String> map){
		String accStartTime = factoryPlanDao.getPrevAccStartTime(map);
		return accStartTime;
	}
	/**
	 * 修改密码
	 */
	public void factoryUpdatePassword(Map<String,String> map){
		factoryPlanDao.factoryUpdatePassword(map);
	}
	/**
	 * 根据计划id和工序名称获取工序计划开始时间
	 * @param map
	 * @return
	 */
	public ProgressDto getPlanStartTimeByProcessNameTwo(Map<String,String> map){
		ProgressDto dto = factoryPlanDao.getPlanStartTimeByProcessName(map);
		return dto;
	}

	public ModelPlan getmodelPlan(int modelPlanId){
		return factoryPlanDao.getmodelPlan(modelPlanId);
	}

	public ModelDto getModel(String modelCode) {
		return factoryPlanDao.getModel(modelCode);
	}
	/**
	 * 获取计划最后一次提交进度是否审核通过
	 * @param modelPlanId
	 * @return
	 */
	public String getAuditResult(Integer  modelPlanId){
		return factoryPlanDao.getAuditResult(modelPlanId);
	}
}
